import {
  dsx
} from '../../tools/datax';
import {
  msg
} from '../../tools/msg';
import {
  dateTool
} from '../../tools/date';
import {
  checkTool
} from '../../tools/check';
import {
  ds
} from '~/tools/data';

Page({
  data: {},
  async onTestTap() {
    const _ = ds.cmd
    const res = await ds.getAll('users', {
      role: _.or(_.eq('delivery'), _.eq('master'))
    })
    res.forEach(u => {
      ds.cloudUpdate('users', u._id, {
        shops: [`${u.shop.id}`]
      })
    })
  },
  async onUpgrateDeliveryFee() {
    const _ = dsx.cmd
    let count = 0,
      total = 0
    do {
      const res = await dsx.coll('orders').where({
        payStatus: _.eq('success'),
        deliveryMan: _.exists(true),
        status: _.in(['已送达', '已退款', '已取消']),
        deliveryFeePaid: _.exists(false).or(_.neq(true))
      }).field({
        _openid: 1
      }).get()
      console.log(res)
      count = res.data.length
      total += count
      for (const d of res.data) {
        console.log(d._id)
        await dsx.cloudUpdate('orders', d._id, {
          deliveryFeePaid: true
        }).then(res => {
          console.log(res)
        }).catch(err => {
          console.error(err)
        })
      }
      console.log("dealed: " + total)
    }
    while (count > 0)
  },
  testReadable() {
    const d = new Date()
    // d.setMonth(6)
    d.setDate(23)
    console.log(dateTool.readable(d.getTime()))
  },
  updateChat() {
    dsx.getAll('chat', {
        _id: dsx.cmd.exists(true)
      })
      .then(async data => {
        for (const c of data) {
          await dsx.cloudUpdate('chat', c._id, {
            sessionOpenId: c._openid
          })
        }
      })
  },
  testDeliveryTips() {
    const date = new Date()
    date.setHours(20)
    date.setMinutes(43)
    console.log(date)
    console.log(this.deliveryTips(date.getTime()))
  },
  deliveryTips(timestamp) {
    const workFromHour = 8,
      work2Hour = 20
    const date = new Date(Number(timestamp))
    const hours = date.getHours()
    if (hours >= workFromHour && hours < work2Hour) {
      date.setHours(hours, date.getMinutes() + 30) // 30 mins after
    } else {
      date.setHours(hours + 24) // the next day
      date.setHours(8)
      date.setMinutes(0)
    }
    return date
  },
  userCmd() {
    wx.cloud.callFunction({
      name: 'userCmd',
      data: {
        cmd: 'findDeliveryUsers',
        orderId: '6d35026063e73e9600005027696b0099'
      }
    }).then(res => {
      console.log(res)
    })
  },

  dateFormat() {
    wx.cloud.callFunction({
      name: 'tools',
      data: {
        action: 'dateTool.format',
        timestamp: new Date().getTime(),
        format: 'M月d日hh:mm'
      }
    }).then(res => {
      console.log(res)
    })
  },

  onLoad(options) {

  },
  onShow() {

  },
  backTap() {
    wx.navigateBack()
  }
})